﻿using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Security;
using System.Net;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace LotusIslandOrderProcessing.model
{
    public class PLC
    {
        static string token = "";


        //PLC访问地址根据情况填写
        static string _url = "https://192.168.5.102/api/jsonrpc";
        static string jsonParam1 = "";
        public PLC()
        {
            _url = "https://192.168.5.102/api/jsonrpc";
        }
        public string Url
        {
            get
            {
                return _url;
            }
            set
            {
                _url = value;
            }
        }
        //写入数据
        public static string PlcProgramWrite(int Category_Number_1, int Category_Number_2, int Category_Number_3, int Category_Number_4, int Category_Number_5, int Category_Number_6, int value4, int value5)
        {
            string sss = "";

            sss = "{\"jsonrpc\": \"2.0\",\"method\": \"PlcProgram.Write\",\"params\":{\"var\":\"\\\"Com_Data\\\".Command.Category_Number_1\",\"value\":" + Category_Number_1 + "},\"id\": 1},{\"jsonrpc\": \"2.0\",\"method\": \"PlcProgram.Write\",\"params\":{\"var\":\"\\\"Com_Data\\\".Command.Category_Number_2\",\"value\":" + Category_Number_2 + "},\"id\": 1},{\"jsonrpc\": \"2.0\",\"method\": \"PlcProgram.Write\",\"params\":{\"var\":\"\\\"Com_Data\\\".Command.Category_Number_3\",\"value\":" + Category_Number_3 + "},\"id\": 1},{\"jsonrpc\": \"2.0\",\"method\": \"PlcProgram.Write\",\"params\":{\"var\":\"\\\"Com_Data\\\".Command.Category_Number_4\",\"value\":" + Category_Number_4 + "},\"id\": 1},{\"jsonrpc\": \"2.0\",\"method\": \"PlcProgram.Write\",\"params\":{\"var\":\"\\\"Com_Data\\\".Command.Category_Number_5\",\"value\":" + Category_Number_5 + "},\"id\": 1},{\"jsonrpc\": \"2.0\",\"method\": \"PlcProgram.Write\",\"params\":{\"var\":\"\\\"Com_Data\\\".Command.Category_Number_6\",\"value\":" + Category_Number_6 + "},\"id\": 1},";
            jsonParam1 = "[{\"jsonrpc\": \"2.0\",\"method\": \"PlcProgram.Write\",\"params\":{\"var\":\"\\\"Com_Data\\\".Command.Action_Request\",\"value\":1},\"id\": 1}," + sss +
                       "{\"jsonrpc\": \"2.0\",\"method\":\"PlcProgram.Write\",\"params\":{\"var\":\"\\\"Com_Data\\\".Command.Complete_Response\",\"value\":" + value4 + "},\"id\": 1}]";
            return jsonParam1;//ClientRequest1(_url, jsonParam1);
        }



        //登录获取TOKEN 每次访问都需要
        public string Login()
        {
            Thread.Sleep(1500);
            jsonParam1 = "[{\"jsonrpc\":\"2.0\",\"method\":\"Api.Login\",\"params\":{\"user\":\"admin\",\"password\":\"123456\"},\"id\":999}]";
            return ClientRequest(_url, jsonParam1);
        }
        public static string PlcProgramred()
        {
            jsonParam1 = "[{\"jsonrpc\": \"2.0\",\"method\": \"PlcProgram.Read\",\"params\":{ \"var\":\"\\\"Data_Com\\\".State.Category_Number\"},\"id\": 1}," +
                "{\"jsonrpc\": \"2.0\",\"method\": \"PlcProgram.Read\",\"params\":{ \"var\":\"\\\"Data_Com\\\".State.Action_Feedback\"},\"id\": 1}," +
                "{\"jsonrpc\": \"2.0\",\"method\": \"PlcProgram.Read\",\"params\":{ \"var\":\"\\\"Data_Com\\\".State.Complete_Request\"},\"id\": 1}," +
                "{\"jsonrpc\": \"2.0\",\"method\": \"PlcProgram.Read\",\"params\":{ \"var\":\"\\\"Data_Com\\\".State.Alarm_Signal\"},\"id\": 1}," +
                "{\"jsonrpc\": \"2.0\",\"method\": \"PlcProgram.Read\",\"params\":{ \"var\":\"\\\"Data_Com\\\".State.Element_1\"},\"id\": 1}]";
            //jsonParam1 = "{\"jsonrpc\": \"2.0\",\"method\": \"PlcProgram.Read\",\"params\":{ \"var\":\"\\\"Data_Com\\\".State.Category_Number\"},\"id\": 1}";
            return ""; // ClientRequest1(_url, jsonParam1);
        }


        //        Action_Feedback Byte    制作回应	0/1
        //Complete_Request Byte    完成请求	0/1
        //Missing_Cup_1 Byte    缺杯1 默认0，缺杯1
        //Missing_Cup_2   Byte 缺杯2
        //Missing_Cup_3 Byte    缺杯3
        //Missing_Gai_1   Byte 缺盖1 默认0，缺盖1
        //Missing_Gai_2   Byte 缺盖2
        //读取PLC故障状态状态
        public string PlcgetOrder_PLCState()
        {

            jsonParam1 = "[{\"jsonrpc\": \"2.0\",\"method\": \"PlcProgram.Read\",\"params\":{ \"var\":\"\\\"Com_Data\\\".State.Action_Feedback\"},\"id\": 1}," +
                "{\"jsonrpc\": \"2.0\",\"method\": \"PlcProgram.Read\",\"params\":{ \"var\":\"\\\"Com_Data\\\".State.Complete_Request\"},\"id\": 1},{\"jsonrpc\": \"2.0\",\"method\": \"PlcProgram.Read\",\"params\":{ \"var\":\"\\\"Com_Data\\\".State.Missing_Cup_1\"},\"id\": 1},{\"jsonrpc\": \"2.0\",\"method\": \"PlcProgram.Read\",\"params\":{ \"var\":\"\\\"Com_Data\\\".State.Missing_Cup_2\"},\"id\": 1},{\"jsonrpc\": \"2.0\",\"method\": \"PlcProgram.Read\",\"params\":{ \"var\":\"\\\"Com_Data\\\".State.Missing_Cup_3\"},\"id\": 1},{\"jsonrpc\": \"2.0\",\"method\": \"PlcProgram.Read\",\"params\":{ \"var\":\"\\\"Com_Data\\\".State.Missing_Gai_1\"},\"id\": 1},{\"jsonrpc\": \"2.0\",\"method\": \"PlcProgram.Read\",\"params\":{ \"var\":\"\\\"Com_Data\\\".Missing_Gai_2\"},\"id\": 1}]";
            return ClientRequest1(_url, jsonParam1);
        }


        //读取PLC中的故障数组
        //Malfunction[0] Byte                        故障0-1-2
        //Malfunction[1] Byte                        缺杯1
        //Malfunction[2] Byte 缺杯2
        //Malfunction[3] Byte                        缺果汁1
        //Malfunction[4] Byte 缺果汁2
        //Malfunction[5] Byte                        冰淇淋机故障1
        //Malfunction[6] Byte 冰淇淋机故障2

        public string PlcgetOrder_Malfunction()
        {

            jsonParam1 = "[{\"jsonrpc\": \"2.0\",\"method\": \"PlcProgram.Read\",\"params\":{ \"var\":\"\\\"Com_Data\\\".State.Malfunction[0]\"},\"id\": 1}" +
                ",{\"jsonrpc\": \"2.0\",\"method\": \"PlcProgram.Read\",\"params\":{ \"var\":\"\\\"Com_Data\\\".State.Malfunction[1]\"},\"id\": 1}," +
                "{\"jsonrpc\": \"2.0\",\"method\": \"PlcProgram.Read\",\"params\":{ \"var\":\"\\\"Com_Data\\\".State.Malfunction[2]\"},\"id\": 1}," +
                "{\"jsonrpc\": \"2.0\",\"method\": \"PlcProgram.Read\",\"params\":{ \"var\":\"\\\"Com_Data\\\".State.Malfunction[3]\"},\"id\": 1}," +
                "{\"jsonrpc\": \"2.0\",\"method\": \"PlcProgram.Read\",\"params\":{ \"var\":\"\\\"Com_Data\\\".State.Malfunction[4]\"},\"id\": 1}," +
                "{\"jsonrpc\": \"2.0\",\"method\": \"PlcProgram.Read\",\"params\":{ \"var\":\"\\\"Com_Data\\\".State.Malfunction[5]\"},\"id\": 1}," +
                "{\"jsonrpc\": \"2.0\",\"method\": \"PlcProgram.Read\",\"params\":{ \"var\":\"\\\"Com_Data\\\".State.Malfunction[0]\"},\"id\": 1}]";
            return ClientRequest1(_url, jsonParam1);
        }

        public string PlcProgramred1()
        {
            jsonParam1 = "[{\"jsonrpc\": \"2.0\",\"method\": \"PlcProgram.Read\",\"params\":{ \"var\":\"\\\"Com_Data\\\".State.Order_Number\"},\"id\": 1}]";
            //jsonParam1 = "{\"jsonrpc\": \"2.0\",\"method\": \"PlcProgram.Read\",\"params\":{ \"var\":\"\\\"Data_Com\\\".State.Category_Number\"},\"id\": 1}";
            return ClientRequest1(_url, jsonParam1);
        }
        public string ping()
        {
            jsonParam1 = "[{\"jsonrpc\":\"2.0\",\"method\":\"Api.Ping\",\"id\":1}]";
            return ClientRequest1(_url, jsonParam1);
        }


        public string Browse()
        {
            jsonParam1 = "[{\"jsonrpc\":\"2.0\",\"method\":\"Api.Browse\",\"id\":1}]";
            return ClientRequest(_url, jsonParam1);
        }
        public string ClientRequest(string Uri, string JsonStr, string Method = "POST")
        {
            try
            {
                var httpRequest = (HttpWebRequest)HttpWebRequest.Create(Uri);
                httpRequest.Method = Method;
                httpRequest.ContentType = "application/json";
                if (Method.ToLower() == "get")
                {
                    httpRequest.ContentType = "application/x-www-form-urlencoded";
                }
                httpRequest.Proxy = null;
                httpRequest.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 6.1; zh-CN; rv:1.9.2.13) Gecko/20101203 Firefox/3.6.13";
                httpRequest.Headers.Add("Accept-Language", "zh-cn,en-us;q=0.8,zh-hk;q=0.6,ja;q=0.4,zh;q=0.2");

                //httpRequest.Headers.Add("X-Auth-Token",token);

                httpRequest.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";

                //如果是发送HTTPS请求  
                if (Uri.StartsWith("https", StringComparison.OrdinalIgnoreCase))
                {
                    ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
                    httpRequest.ProtocolVersion = HttpVersion.Version10;
#pragma warning disable CS0618 // 类型或成员已过时
                    ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
#pragma warning restore CS0618 // 类型或成员已过时
                }
                else
                {
                    ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
                    ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
                }

                if (!string.IsNullOrEmpty(JsonStr))
                {
                    using (var dataStream = new StreamWriter(httpRequest.GetRequestStream()))
                    {
                        dataStream.Write(JsonStr);
                        dataStream.Flush();
                        dataStream.Close();
                    }
                }

                var httpResponse = (HttpWebResponse)httpRequest.GetResponse();
                using (var dataStream = new StreamReader(httpResponse.GetResponseStream()))
                {
                    var result = dataStream.ReadToEnd();

                    return result;
                }
            }
            catch (Exception ex)
            {
                WriteLogs("订单流程", "操作异常：" + ex.Message, "");
                return "{\"error\":\"" + ex.Message + "\"}";
            }
        }

        public string ClientRequest1(string Uri, string JsonStr, string Method = "POST")
        {
            try
            {
                var httpRequest = (HttpWebRequest)HttpWebRequest.Create(Uri);
                httpRequest.Method = Method;
                httpRequest.ContentType = "application/json";
                if (Method.ToLower() == "get")
                {
                    httpRequest.ContentType = "application/x-www-form-urlencoded";
                }
                httpRequest.Proxy = null;
                httpRequest.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 6.1; zh-CN; rv:1.9.2.13) Gecko/20101203 Firefox/3.6.13";
                httpRequest.Headers.Add("Accept-Language", "zh-cn,en-us;q=0.8,zh-hk;q=0.6,ja;q=0.4,zh;q=0.2");
                //httpRequest.Headers.Add("Authorization", "X-Token " + token);
                while (true)
                {
                    token = GETtoken(Login());
                    if (token != "")
                    {
                        httpRequest.Headers.Add("X-Auth-Token", token);

                        break;
                        //httpRequest.Headers.Add("Authorization", "X-Auth-Token" + token);
                    }
                }




                httpRequest.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
                //WEdSR / aBIFLcGgjNZWgHcJwsd75q
                //p7YHuPQ5oPTRTO / RyMeRWZNyQopZ
                //如果是发送HTTPS请求  
                if (Uri.StartsWith("https", StringComparison.OrdinalIgnoreCase))
                {
                    ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
                    httpRequest.ProtocolVersion = HttpVersion.Version10;
#pragma warning disable CS0618 // 类型或成员已过时
                    ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
#pragma warning restore CS0618 // 类型或成员已过时
                }
                else
                {
                    ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
                    ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
                }

                if (!string.IsNullOrEmpty(JsonStr))
                {
                    using (var dataStream = new StreamWriter(httpRequest.GetRequestStream()))
                    {
                        dataStream.Write(JsonStr);
                        dataStream.Flush();
                        dataStream.Close();
                    }
                }

                var httpResponse = (HttpWebResponse)httpRequest.GetResponse();
                using (var dataStream = new StreamReader(httpResponse.GetResponseStream()))
                {
                    var result = dataStream.ReadToEnd();

                    return result;
                }
            }
            catch (Exception ex)
            {

                return "{\"error\":\"" + ex.Message + "\"}";
            }
        }
        private bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
        {
            return true; //总是接受  
        }

        public string GETtoken(string jsonText)
        {
            try
            {

                JArray jArray = (JArray)JsonConvert.DeserializeObject(jsonText);

                string str = jArray[0]["result"].ToString();

                JObject jo = (JObject)JsonConvert.DeserializeObject(str);

                var lng = (string)jo["token"];
                token = lng;

            }
            catch (Exception ex)
            {
                token = "";

            }

            return token;
        }
        /// <summary>
        /// 日志部分
        /// </summary>
        /// <param name="fileName"></param>
        /// <param name="type"></param>
        /// <param name="content"></param>
        public static void WriteLogs(string fileName, string type, string content)
        {
            string path = AppDomain.CurrentDomain.BaseDirectory;
            if (!string.IsNullOrEmpty(path))
            {
                path = AppDomain.CurrentDomain.BaseDirectory + fileName;
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }
                path = path + "\\" + DateTime.Now.ToString("yyyyMMdd");
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }
                path = path + "\\" + DateTime.Now.ToString("yyyyMMdd") + ".txt";
                if (!File.Exists(path))
                {
                    FileStream fs = File.Create(path);
                    fs.Close();
                }
                if (File.Exists(path))
                {
                    StreamWriter sw = new StreamWriter(path, true, System.Text.Encoding.Default);
                    sw.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + type + "-->" + content);
                    //  sw.WriteLine("----------------------------------------");
                    sw.Close();
                }
            }
        }
    }
}
